<?php

require_once ROOT_SERVICES_MODEL . DS . 'models_warehouse.php';
require_once ROOT_SERVICES_MODEL . DS . 'models_setting.php';
require_once ROOT_SERVICES_MODEL . DS . 'models_common.php';
require_once ROOT_SERVICES . DS . 'oms_shipping.php';
require_once ROOT_SERVICES . DS . 'shipping_provider_interface.php';

class service_interface {

    const STATUS_SHIPPED = 5;

    private static function _verify_get_stock($params) {
        $sign = isset($params['sign']) ? $params['sign'] : null;
        if (isset($sign)) {
            $sku = isset($params['sku']) ? $params['sku'] : null;
            return ($sign === md5($sku . API_KEY));
        }
        return FALSE;
    }

    public static function get_stock($db, $cache, $params = array()) {

        if (self::_verify_get_stock($params)) {

            $warehouse = new models_warehouse($db, $cache);
            if ($warehouse->check_exist_sku($params['sku'])) {
                $stock = $warehouse->get_stock($params['sku']);
                $amount = isset($stock["STOCK"]) ? $stock["STOCK"] : 0;

                return array('error' => 0, 'message' => '', 'data' => $amount);
            }
            return array('error' => 2, 'message' => 'sku dose not exist', 'data' => '');
        } else {
            return array('error' => 3, 'message' => 'Invalid API Key', 'data' => '');
        }
    }

    public static function get_status_provider($db, $cache, $params = array()) {

        $shipment = array(
            'id_shipment_provider' => $params['id'],
            'shipment_provider_name' => $params['name'],
            'tracking_number' => $params['tracking_number'],
            'url' => isset($params['url']) ? $params['url'] : '');

        $country = global_vars::instance()->get('local_db');
        $classname = "shipping_provider_{$shipment['id_shipment_provider']}";
        $shipping_provider_file = ROOT_SERVICES . DS . "shipping_provider" . DS . $country . DS . $classname . ".php";

        $data = array();
        if (file_exists($shipping_provider_file)) {
            include $shipping_provider_file;
            $class = new $classname($shipment);
            if ($class instanceof shipping_provider_interface) {
                $result = $class->get_status_shipping();
                if (isset($params['format']) && $params['format'] == 'html') {
                    $data = self::_get_html_status_shipment_provider($result['status_list']);
                } else {
                    $data = $result;
                }
            }
        }

        return array('error' => 0, 'messsage' => '', 'data' => $data);
    }

    private static function _get_html_status_shipment_provider($list_status) {
        $html = '';
        foreach ($list_status as $status) {
            $html .= "<li class=\"o_showable_shipment\"><span class=\"status_time\">{$status['time']}</span><span class=\"status_text\">{$status['status']}</span></li>";
        }
        return $html;
    }

    public static function get_status_shipping($db, $cache, $params = array()) {
        if (isset($params['order_id'])) {
            $oms_shipping = new oms_shipping($db, $cache);
            $result = $oms_shipping->get_status_shipping($params['order_id']);
            $data = '';

            if (isset($params['format']) && $params['format'] == 'html') {
                if (empty($result['status_items'])) {
                    return array('error' => 0, 'messsage' => 'order dose not exist', 'data' => '');
                } else {
                    $data = self::_gen_html($result, $db);
                }
            } else {
                $data = $result;
            }

            global_vars::instance()->get('models_common')->insert_order_log($params['order_id']);

            return array('error' => 0, 'messsage' => '', 'data' => $data);
        } else {
            return array('error' => 1, 'messsage' => 'no parameter', 'data' => '');
        }
    }

    public static function _gen_html($result) {

        $setting = global_vars::instance()->get('setting');
        $models_common = global_vars::instance()->get('models_common');

        $greeting = $setting->get('greetings');
        $greeting = str_replace('@customer_name', $result['order']['customer_first_name'], $greeting);
        $greeting = str_replace('@customer_order_tracking', $result['order']['order_nr'], $greeting);

        $header_order = "
            <div class=\"order_header\">
                    <h1>{$setting->get('title_order_tracking')}</h1>
                    <h3>{$greeting}</h3>
                    <label>{$setting->get('order_date')}:</label><span> {$result['order']['created_at']}</span>
                    <label>{$setting->get('payment_method')}:</label><span>{$models_common->get_map_paymentmenthod($result['order']['payment_method'])}</span>
            </div>";

        $process_bar = "<div class=\"order_process\">" . self::_get_processbar($result['order']) . "</div>";

        $content = "
	<div class=\"order_content\">
		<table style=\"border-bottom: 1px solid #ddd;\">
			<thead><tr><th class=\"col-1\">{$setting->get('product_name')}</th><th class=\"col-2\">{$setting->get('quality')}</th><th class=\"col-3\">{$setting->get('current_status')}</th></tr></thead>
			<tbody class=\"list_item\">
                        @list_item
			</tbody>
		</table>
	</div>";

        $content_table = '';
        $firt_row_package = true;
        $row_same_status = 0;
        $cur_row = 1;
        $num_rows = count($result['status_items']);
        $pre_item = $result['status_items'][0];

        foreach ($result['status_items'] as $item) {

            $row = '';
            $is_multi_package = false;
            if (count($item['list_package']) > 1) {
                /**/
                $str_replace = '<td rowspan="' . $row_same_status . '">' . self::_gen_html_list_status($pre_item['list_package'][0]) . '</td>';
                $content_table = str_replace('@first_row_package', $str_replace, $content_table);
                /**/

                $fist_row_item = true;
                $is_multi_package = count($item['list_package']) > 1 ? TRUE : FALSE;
                $package_in_item = 1;
                foreach ($item['list_package'] as $package) {
                    $row .= '<tr>';
                    $row .= $fist_row_item ? '<td ROWSPAN=' . count($item['list_package']) . '>' . $item['name'] . '</td>' : '';
                    $row .= '<td>' . $package['amount'] . ($is_multi_package ? ' ( ' . $setting->get('package') . $package_in_item++ . ' )' : '') . '</td>';
                    $row .= '<td>' . self::_gen_html_list_status($package) . '</td>';
                    $row .= '</tr>';
                    $fist_row_item = FALSE;
                }
                $firt_row_package = TRUE;
                $row_same_status = 0;
            } else {

                if ($item['list_package'][0]['last_status_in_wh'] != $pre_item['list_package'][0]['last_status_in_wh']) {
                    $str_replace = '<td rowspan="' . $row_same_status . '">' . self::_gen_html_list_status($pre_item['list_package'][0]) . '</td>';
                    $content_table = str_replace('@first_row_package', $str_replace, $content_table);
                    $firt_row_package = TRUE;
                    $row_same_status = 0;
                }

                $row .= '<tr>';
                $row .= '<td>' . $item['name'] . '</td>';
                $row .= '<td class="amount">' . $item['list_package'][0]['amount'] . '</td>';
                $row .= $firt_row_package ? '@first_row_package' : '';
                $row .= '</tr>';

                $firt_row_package = FALSE;
                $row_same_status++;
            }

            $pre_item = $item;
            $content_table .= $row;
        }
        $status_lastest = '<td rowspan="' . $row_same_status . '">' . self::_gen_html_list_status($item['list_package'][0]) . '</td>';
        $content_table = str_replace('@first_row_package', $status_lastest, $content_table);

        $content = str_replace('@list_item', $content_table, $content);

        $html = $header_order . $process_bar . $content;
        return $html;
    }

    private static function _gen_html_list_status($package) {

        $setting = global_vars::instance()->get('setting');
        $first_line = true;
        $list_status = $package['list_status'];
        $html = '<ul>';
        $pre_status = -1;

        foreach ($list_status as $status) {
            if ($pre_status != $status['id']) {
                $text = $status['status'];
                if ($status['id'] == service_interface::STATUS_SHIPPED) {
                    $id_shipment = $package['fk_shipment_provider'];
                    $tracking_num = $package['tracking_number'];
                    $link = "<a href='#' id=\"a_{$id_shipment}_{$tracking_num}\" onclick=\"getShipmentProvider('{$id_shipment}','{$package['shipment_provider_name']}','{$tracking_num}')\">{$setting->get('track_shipping_status')}</a>";
                    $text = str_replace('@tracking_number', $package['tracking_number'], $text);
                    $text = str_replace('@view_detail', $link, $text);
                    $text .= "<ul id=\"{$id_shipment}_{$tracking_num}\">";
                    $text .= "</ul>";
                }

                $html .= "<li class=\"" . ($first_line ? '' : 'o_showable') . "\" ><span class=\"status_time\">{$status['time']}</span><span class=\"status_text\">{$text}</span></li>";
                $first_line = false;
            }
            $pre_status = $status['id'];
        }
        $html .= '<li><a class="view_more" href="#"></a></li>';
        $html .= '</ul>';
        return $html;
    }

    private static function _get_processbar($order) {
        
        $process_bar_html = '';
        if (isset($order['list_status_order'][0])) {

            $st = global_vars::instance()->get('setting');

            $delivery = array('1' => '25%', '2' => '50%', '8' => '75%', '9' => '100%');
            $sourcing = array('1' => '20%', '2' => '40%', '5' => '60%', '6' => '60%', '7' => '60%', '10' => '60%', '12' => '60%', '14' => '60%', '8' => '100%', '9' => '100%');
            $canceled = array('1' => '50%', '3' => '100%', '4' => '100%', '13' => '100%');

            $delivery_text = array('1' => $st->get('new'), '2' => $st->get('verified'),
                '8' => $st->get('shipped'), '9' => $st->get('delivered'));

            $sourcing_text = array('1' => $st->get('new'), '2' => $st->get('verified'), '5' => $st->get('sourcing'), '6' => $st->get('hunter'),
                '7' => $st->get('logistics'), '10' => $st->get('all_items_processed'), '12' => $st->get('blocked'), '14' => $st->get('updated'),
                '8' => $st->get('shipped'), '9' => $st->get('delivered'));

            $canceled_text = array('1' => $st->get('new'), '3' => $st->get('fraud'), '4' => $st->get('cancelled'), '13' => $st->get('returned'));

            $last_so = $order['list_status_order'][0];
            $list_so = $order['list_status_order'];

            $case_apply = array();
            $case_apply_text = array();
            $case_enter = 0;
            $class_width_text = '';

            if (in_array('5', $list_so)) {
                $case_enter = 2;
            }

            if (in_array('3', $list_so) || in_array('4', $list_so) || in_array('13', $list_so)) {
                $case_enter = 3;
            }

            if ($case_enter == 1 || array_key_exists($last_so, $delivery)) {
                $case_apply = $delivery;
                $case_apply_text = $delivery_text;
                $class_width_text = 'width_25';
            }
            if ($case_enter == 2 || array_key_exists($last_so, $sourcing)) {
                $case_apply = $sourcing;
                $case_apply_text = $sourcing_text;
                $class_width_text = 'width_20';
            }
            if ($case_enter == 3 || array_key_exists($last_so, $canceled)) {
                $case_apply = $canceled;
                $case_apply_text = $canceled_text;
                $class_width_text = 'width_50';
            }

            $process_bar_html = "<div class=\"order_process_text\"><ul>";
            $pre_text = '';


            foreach ($case_apply_text as $id => $text) {
                if ($text != $pre_text)
                    $process_bar_html .= "<li class={$class_width_text}><span>{$text}</span></li>";
                $pre_text = $text;
            }
            $process_bar_html .= "</ul><div style=\"clear:both\"></div></div>";

            $process_bar_html .= "
            <div class=\"order_process_bar\">
            <div class=\"bar\" style=\"width:" . $case_apply[$last_so] . "\">&nbsp;</div>
            </div>";
        }
        return $process_bar_html;
    }

}

?>
